import pool from "@/lib/db";

const pageModule = {
  getById: async (id) => {
    const sql = 'SELECT * FROM pages WHERE id = ?';
    const [rows] = await pool.query(sql, [id]);
    return rows[0];
  },
  getBySlug: async (slug) => {
    const sql = 'SELECT * FROM pages WHERE slug = ?';
    const [rows] = await pool.query(sql, [slug]);
    return rows[0];
  },
  getAll: async ({limit = 10, offset = 0} = {}) => {
    const sql = 'SELECT * FROM pages ORDER BY created_at DESC LIMIT ? OFFSET ?';
    const [rows] = await pool.query(sql, [limit, offset]);
    return rows;
  },
  getSlugs: async () => {
    const sql = 'SELECT slug FROM pages';
    const [rows] = await pool.query(sql);
    return rows.map(row => row.slug);
  },
  count: async () => {
    const sql = 'SELECT COUNT(*) as count FROM pages';
    const [rows] = await pool.query(sql);
    return rows[0].count;
  },
  update: async ({id, slug, status, cover, title, description, content, meta_title, meta_description, sort, template}) => {
    const sql = ` UPDATE pages SET slug = ?, status = ?, cover = ?, title = ?, description = ?, content = ?, meta_title = ?, meta_description = ?, sort = ?, template = ? WHERE id = ? `;
    const [result] = await pool.query(sql, [slug, status, cover, title, description, content, meta_title, meta_description, sort, template, id]);
    return result.affectedRows > 0;
  },
  create: async ({slug, status, cover, title, description, content, meta_title, meta_description, sort, template}) => {
    const sql = ` INSERT INTO pages (slug, status, cover, title, description, content, meta_title, meta_description, sort, template) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `;
    const [result] = await pool.query(sql, [slug, status, cover, title, description, content, meta_title, meta_description, sort, template]);
    return result.insertId;
  },
  deleteById: async (id) => {
    const sql = 'DELETE FROM pages WHERE id = ?';
    const [result] = await pool.query(sql, [id]);
    return result.affectedRows > 0;
  },
}

export default pageModule;